import configparser
import math
import time
from sqlalchemy import Column, String, create_engine, Integer
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import requests

headers = {
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36",
    "cookie": ""
}

# 创建对象的基类:
Base = declarative_base()


# 定义User对象:
class video_list(Base):
    # 表的名字:
    __tablename__ = 'video_list'

    # 表的结构:
    bvid = Column(String(20), primary_key=True)
    typeid = Column(Integer)
    author = Column(String(20))
    mid = Column(Integer)
    created = Column(Integer)
    length = Column(String(20))
    title = Column(String(100))
    is_union_video = Column(Integer)


def get_video_d(cookie, i, s):
    url = "http://api.bilibili.com/x/space/arc/search?mid={}&pn={}&ps=30"
    headers['cookie'] = cookie
    res = requests.get(url.format(i, s), headers=headers)
    res = res.json()
    bv_list = bvid_list()
    if res.get("code") == 0:
        for x in res.get("data").get("list").get("vlist"):
            if x.get("bvid") not in bv_list:
                engine = create_engine("mysql+pymysql://root:Aa380562113.@192.168.2.8:3306/bilibili?charset=utf8")
                DBSession = sessionmaker(bind=engine)
                session = DBSession()
                new_video = video_list(bvid=x.get("bvid"),
                                       typeid=x.get("typeid"),
                                       author=x.get("author"),
                                       mid=x.get("mid"),
                                       created=x.get("created"),
                                       length=x.get("length"),
                                       title=x.get("title"),
                                       is_union_video=x.get("is_union_video"))
                session.add(new_video)
                session.commit()
                session.close()
        time.sleep(5)
        return res.get("data").get("page").get("count")
    else:
        print(res.get("message"))
        return -1


def git_video(cookie, id):
    cou = get_video_d(cookie, id, 1)
    if cou > 0 and cou <= 30:
        pass
    elif cou > 30:
        for i in range(2, math.ceil(cou / 30) + 1):
            get_video_d(cookie, id, i)


def config():
    ck = []
    cp = configparser.RawConfigParser()
    cp.read('/root/bilibili/config.ini')
    # ck.append(cp.get('bilibili', 'cookie1'))
    # ck.append(cp.get('bilibili', 'cookie2'))
    ck.append(cp.get('bilibili', 'cookie3'))
    # up_list = cp.get('up_list', 'up_list')
    return ck


def bvid_list():
    bv_list = []
    engine = create_engine("mysql+pymysql://root:Aa380562113.@192.168.2.8:3306/bilibili?charset=utf8")
    DBSession = sessionmaker(bind=engine)
    session = DBSession()
    # 创建Query查询，filter是where条件，最后调用one()返回唯一行，如果调用all()则返回所有行:
    bv = session.query(video_list).filter().all()
    for i in bv:
        bv_list.append(i.bvid)
    session.close()
    return bv_list


if __name__ == '__main__':
    cookie = config()
    for i in cookie:
        git_video(i, 903059)
